import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http"
import { Router } from "@angular/router"

@Component({
  selector: 'app-sigin',
  templateUrl: './sigin.component.html',
  styleUrls: ['./sigin.component.css']
})
export class SiginComponent implements OnInit {
  siginupFrom = {
    email: '',
    password: ''
  }

  err_name_msg: string = ''

  sign() {
    const fromData = this.siginupFrom
    console.log(fromData)
    this.http.post("http://localhost:3000/session", fromData).toPromise().then((data: any) => {
      console.log(data)
      // window.alert("用户注册成功！")
      window.localStorage.setItem("auth_token", data.token)
      window.localStorage.setItem("user_info", JSON.stringify(data.user))
      this.router.navigate(['/'])   //跳转到首页
    }).catch(err => {//捕获异常
      if (err) {
        console.log(err)
        if (err.status == 401) {
          this.err_name_msg = '登录失败，请重新输入'
        }
      }
    })
  }
  constructor(
    private http: HttpClient,
    private router: Router
  ) { }

  ngOnInit() {
  }

}
